package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

@Service(interfaceClass = ValidateCodeService.class)
@Transactional
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private JedisPool jedisPool;

    @Override//发送预约验证码
    public void sendCode(String telephone) {
//        String string = ValidateCodeUtils.generateValidateCode4String(4);
        String string = "111111";
        try {
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,string);
//            sendMessage(telephone,SMSUtils.VALIDATE_CODE);
            //将验证码存入redis
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,
                    300,string);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    @Override//发送登录验证码
    public void loginCode(String telephone) {
        String string = "222222";
        try {
//            sendMessage(telephone,SMSUtils.VALIDATE_CODE);
            //将验证码存入redis
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,
                    300,string);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    @Override//校验验证码
    public boolean checkCode(String s, String validateCode) {
        String redisCode = jedisPool.getResource().get(s);
        //归还jedis
        jedisPool.close();
        if(validateCode==null||!validateCode.equalsIgnoreCase(redisCode)){
            return false;
        }
        return true;
    }

    //发送短信
    public void sendMessage(String telephone,String messageType) throws ClientException {
        String string = ValidateCodeUtils.generateValidateCode4String(4);
        SMSUtils.sendShortMessage(messageType,telephone,string);
    }


}
